import Koa from "koa";
import KoaBody from "koa-body";
// const logger = require("koa-logger");

import routerInit from "./routes/index";
const app = new Koa();
// error handler
// onerror(app)
// middlewares
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set(
    "Access-Control-Allow-Headers",
    "Content-Type, Content-Length,token,proxy_url,type,header,Authorization, Accept, X-Requested-With , yourHeaderFeild"
  );
  ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
  if (ctx.method == "OPTIONS") {
    ctx.body = 200;
  } else {
    await next();
  }
});
app.use(
  KoaBody({
    multipart: true, //  支持文件上传发
    formidable: {
      maxFileSize: 200 * 1024 * 1024, // 设置   上传文件大小最大限制，默认2M
    },
  })
);
// app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));

// logger
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

// routes
routerInit(app);

// error-handling
app.on("error", (err, ctx) => {
  console.error("server  error", err, ctx);
});

export default app;
